package com.miracle.java2110;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author rwg
 */
public class QinuiUtils {

    public static String accessKey = "BdbVeV-HZ5AVaYesmWKfU_ndsc-Gdfb0ZBE-XdeK";
    public static String secretKey = "e4R3HWYwigINcREyul8Xx-Wo--G26thpMSnCeakn";
    public static String bucket = "rwg";

    public static void uploadLoclFile2Qiniu(String localFilePath, String uploadFileName) {
        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        Response response = null;
        try {
            response = uploadManager.put(localFilePath, uploadFileName, upToken);

            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

    }

    public static void uploadBytes2Qiniu(byte[] bytes, String uploadFileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        Response response = null;
        try {
            response = uploadManager.put(bytes, uploadFileName, upToken);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    public static void main(String[] args) throws IOException {

        byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\Desktop\\3.jpg"));

        uploadBytes2Qiniu(bytes, "3.jpg");

    }
}
